package cn.huiyunche.admin.controller;

import cn.huiyunche.admin.utils.AdminUtils;
import cn.huiyunche.base.service.utils.HttpRequestUtil;
import cn.huiyunche.base.service.vo.Result;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 提供给node权限校验使用
 * @author hdy [Tuffy]
 *
 */
@Controller
@RequestMapping("/node")
public class Admin4NodeController {

	/**
	 * 获取系统票据
	 * @param host 主机
	 * @return 结果集
	 */
	@RequestMapping(value = "/legality", method = RequestMethod.POST)
	@ResponseBody
	public Result<String> legality(String phone, String password, String host) {
		Result<String> r = new Result<>(false);
		JSONObject resultJSON = new JSONObject();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("phone", phone);
		params.put("password", password);
		params.put("usertype", 50);
		params.put("clienttype", "pc");
		params.put("devicetype", "pc");
		params.put("uuid", "11111111111");
		String result = HttpRequestUtil.sendHttpPost(host + "/login/userlogin", params, 20000);
		if (StringUtils.isNotBlank(result)) {
			resultJSON = JSONObject.parseObject(result);
			if (resultJSON.getBooleanValue("success")) {
				String data = resultJSON.getString("data");
				if (StringUtils.isNotBlank(data)) {
					JSONObject dataJSON = JSONObject.parseObject(data);
					if (dataJSON.getBooleanValue("success")) {
						JSONObject authorizationData = dataJSON.getJSONObject("data");
						if (null != authorizationData) {
							r.setData(authorizationData.getString("Authorization"));
							r.setSuccess(true);
						}
					}
				}
			}
		}
		return r;
	}

	/**
	 * 菜单校验
	 * @param request 请求
	 * @return 结果集
	 */
	@RequestMapping(value = "/menu", method = RequestMethod.GET)
	@ResponseBody
	public Result<String> checkMenu(HttpServletRequest request) {
		Result<String> r = new Result<>(false);
		String menu = request.getHeader("menu");
		Long menuVal = NumberUtils.toLong(menu, 0L);
		List<Long> menuList = AdminUtils.userMenuList();
		for (Long l : menuList) {
			if (l == menuVal) {
				r.setSuccess(true);
				return r;
			}
		}
		return r;
	}
}
